const axios = require("axios");
const assert = require("assert");

// 测试配置
const BASE_URL = "http://localhost:3001";
const ADMIN_TOKEN =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbm5hbWUiOiJhZG1pbiIsIl9pZCI6IjY3MjNhY2Q1YTY2NTdmNTBiODZjYmNhOSIsImFkbWluaWQiOiJhZG1pbl8yZTA2ZTI4Yy01YzY3LTQwZmQtYTk3MC03YzBmNTk2YmRlYjciLCJpYXQiOjE3NTUxNTY5ODcsImV4cCI6MTc1NTE4NTc4N30.qTAhA1zSHd7jbGtiJtEIEQus-5L8yDnTGt0GICaezjU"; // 实际的管理员token

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
    token: ADMIN_TOKEN,
  },
});

// 测试数据
let testData = {
  customerId: null,
  leadId: null,
  opportunityId: null,
  ticketId: null,
  campaignId: null,
  followupId: null,
};

/**
 * CRM客户管理API测试
 */
async function testCustomerAPI() {
  console.log("\n=== 测试客户管理API ===");

  try {
    // 生成唯一的测试数据
    const timestamp = Date.now();
    const uniquePhone = `138${timestamp.toString().slice(-8)}`;
    const uniqueEmail = `test${timestamp}@example.com`;

    // 1. 创建客户
    console.log("1. 测试创建客户...");
    const createResponse = await api.post("/admin/crm/customers", {
      name: `测试客户${timestamp}`,
      phone: uniquePhone,
      email: uniqueEmail,
      company: "测试公司",
      source: "网站",
      status: "潜在客户",
      tags: ["测试", "API"],
      notes: "这是一个测试客户",
    });
    assert.strictEqual(createResponse.data.code, "200");
    testData.customerId = createResponse.data.data._id;
    console.log("✓ 创建客户成功");

    // 2. 获取客户列表
    console.log("2. 测试获取客户列表...");
    const listResponse = await api.get(
      "/admin/crm/customers?page=1&pageSize=10"
    );
    assert.strictEqual(listResponse.data.code, "200");
    assert(listResponse.data.data.list.length > 0);
    console.log("✓ 获取客户列表成功");

    // 3. 获取单个客户
    console.log("3. 测试获取单个客户...");
    const getResponse = await api.get(
      `/admin/crm/customers/${testData.customerId}`
    );
    assert.strictEqual(getResponse.data.code, "200");
    assert.strictEqual(getResponse.data.data.name, `测试客户${timestamp}`);
    console.log("✓ 获取单个客户成功");

    // 4. 更新客户
    console.log("4. 测试更新客户...");
    const updateResponse = await api.put(
      `/admin/crm/customers/${testData.customerId}`,
      {
        name: "更新测试客户",
        status: "活跃客户",
      }
    );
    assert.strictEqual(updateResponse.data.code, "200");
    console.log("✓ 更新客户成功");

    console.log("✅ 客户管理API测试通过");
  } catch (error) {
    console.error(
      "❌ 客户管理API测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * CRM线索管理API测试
 */
async function testLeadAPI() {
  console.log("\n=== 测试线索管理API ===");

  try {
    // 生成唯一的线索测试数据
    const leadTimestamp = Date.now();
    const uniqueLeadPhone = `139${leadTimestamp.toString().slice(-8)}`;
    const uniqueLeadEmail = `lead${leadTimestamp}@example.com`;

    // 1. 创建线索
    console.log("1. 测试创建线索...");
    const createResponse = await api.post("/admin/crm/leads", {
      name: `测试线索${leadTimestamp}`,
      phone: uniqueLeadPhone,
      email: uniqueLeadEmail,
      company: "线索公司",
      source: "广告",
      status: "新线索",
      score: 80,
      tags: ["高质量", "测试"],
      notes: "这是一个测试线索",
    });
    assert.strictEqual(createResponse.data.code, "200");
    testData.leadId = createResponse.data.data._id;
    console.log("✓ 创建线索成功");

    // 2. 获取线索列表
    console.log("2. 测试获取线索列表...");
    const listResponse = await api.get("/admin/crm/leads?page=1&pageSize=10");
    assert.strictEqual(listResponse.data.code, "200");
    console.log("✓ 获取线索列表成功");

    // 3. 转换线索为客户
    console.log("3. 测试转换线索为客户...");
    const convertResponse = await api.post(
      `/admin/crm/leads/${testData.leadId}/convert`
    );
    assert.strictEqual(convertResponse.data.code, "200");
    console.log("✓ 转换线索为客户成功");

    console.log("✅ 线索管理API测试通过");
  } catch (error) {
    console.error(
      "❌ 线索管理API测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * CRM商机管理API测试
 */
async function testOpportunityAPI() {
  console.log("\n=== 测试商机管理API ===");

  try {
    // 1. 创建商机
    console.log("1. 测试创建商机...");
    const createResponse = await api.post("/admin/crm/opportunities", {
      customerId: testData.customerId,
      title: "测试商机",
      description: "这是一个测试商机",
      value: 50000,
      stage: "初步接触",
      status: "进行中",
      probability: 60,
      expectedCloseDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天后
    });
    assert.strictEqual(createResponse.data.code, "200");
    testData.opportunityId = createResponse.data.data._id;
    console.log("✓ 创建商机成功");

    // 2. 获取商机列表
    console.log("2. 测试获取商机列表...");
    const listResponse = await api.get(
      "/admin/crm/opportunities?page=1&pageSize=10"
    );
    assert.strictEqual(listResponse.data.code, "200");
    console.log("✓ 获取商机列表成功");

    // 3. 更新商机阶段
    console.log("3. 测试更新商机...");
    const updateResponse = await api.put(
      `/admin/crm/opportunities/${testData.opportunityId}`,
      {
        stage: "需求确认",
        probability: 70,
      }
    );
    assert.strictEqual(updateResponse.data.code, "200");
    console.log("✓ 更新商机成功");

    console.log("✅ 商机管理API测试通过");
  } catch (error) {
    console.error(
      "❌ 商机管理API测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * CRM工单管理API测试
 */
async function testTicketAPI() {
  console.log("\n=== 测试工单管理API ===");

  try {
    // 1. 创建工单
    console.log("1. 测试创建工单...");
    const createResponse = await api.post("/admin/crm/tickets", {
      customerId: testData.customerId,
      title: "测试工单",
      description: "这是一个测试工单",
      category: "技术支持",
      priority: "中",
      status: "待处理",
    });
    assert.strictEqual(createResponse.data.code, "200");
    testData.ticketId = createResponse.data.data._id;
    console.log("✓ 创建工单成功");

    // 2. 获取工单列表
    console.log("2. 测试获取工单列表...");
    const listResponse = await api.get("/admin/crm/tickets?page=1&pageSize=10");
    assert.strictEqual(listResponse.data.code, "200");
    console.log("✓ 获取工单列表成功");

    // 3. 分配工单
    console.log("3. 测试分配工单...");
    const assignResponse = await api.post(
      `/admin/crm/tickets/${testData.ticketId}/assign`,
      {
        assignedTo: "6723acd5a6657f50b86cbca9", // 使用实际的管理员ID
      }
    );
    assert.strictEqual(assignResponse.data.code, "200");
    console.log("✓ 分配工单成功");

    console.log("✅ 工单管理API测试通过");
  } catch (error) {
    console.error(
      "❌ 工单管理API测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * CRM营销活动API测试
 */
async function testCampaignAPI() {
  console.log("\n=== 测试营销活动API ===");

  try {
    // 1. 创建营销活动
    console.log("1. 测试创建营销活动...");
    const createResponse = await api.post("/admin/crm/campaigns", {
      name: "测试营销活动",
      description: "这是一个测试营销活动",
      type: "邮件营销",
      status: "草稿",
      startDate: new Date(),
      endDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 7天后
      budget: 10000,
      targetAudience: ["潜在客户", "活跃客户"],
    });
    assert.strictEqual(createResponse.data.code, "200");
    testData.campaignId = createResponse.data.data._id;
    console.log("✓ 创建营销活动成功");

    // 2. 获取营销活动列表
    console.log("2. 测试获取营销活动列表...");
    const listResponse = await api.get(
      "/admin/crm/campaigns?page=1&pageSize=10"
    );
    assert.strictEqual(listResponse.data.code, "200");
    console.log("✓ 获取营销活动列表成功");

    // 3. 执行营销活动
    console.log("3. 测试执行营销活动...");
    const executeResponse = await api.post(
      `/admin/crm/campaigns/${testData.campaignId}/execute`,
      {
        customerIds: [testData.customerId], // 传递客户ID列表
      }
    );
    assert.strictEqual(executeResponse.data.code, "200");
    console.log("✓ 执行营销活动成功");

    console.log("✅ 营销活动API测试通过");
  } catch (error) {
    console.error(
      "❌ 营销活动API测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * CRM跟进记录API测试
 */
async function testFollowupAPI() {
  console.log("\n=== 测试跟进记录API ===");

  try {
    // 1. 创建跟进记录
    console.log("1. 测试创建跟进记录...");
    const createResponse = await api.post("/admin/crm/followups", {
      opportunityId: testData.opportunityId,
      type: "电话",
      content: "与客户进行了电话沟通，了解了具体需求",
      nextAction: "发送产品方案",
      nextFollowUp: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 3天后
    });
    assert.strictEqual(createResponse.data.code, "200");
    testData.followupId = createResponse.data.data._id;
    console.log("✓ 创建跟进记录成功");

    // 2. 获取跟进记录列表
    console.log("2. 测试获取跟进记录列表...");
    const listResponse = await api.get(
      "/admin/crm/followups?page=1&pageSize=10"
    );
    assert.strictEqual(listResponse.data.code, "200");
    console.log("✓ 获取跟进记录列表成功");

    // 3. 获取商机的跟进记录
    console.log("3. 测试获取商机跟进记录...");
    const opportunityFollowupsResponse = await api.get(
      `/admin/crm/followups/opportunity/${testData.opportunityId}`
    );
    assert.strictEqual(opportunityFollowupsResponse.data.code, "200");
    console.log("✓ 获取商机跟进记录成功");

    console.log("✅ 跟进记录API测试通过");
  } catch (error) {
    console.error(
      "❌ 跟进记录API测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * CRM系统集成API测试
 */
async function testIntegrationAPI() {
  console.log("\n=== 测试系统集成API ===");

  try {
    // 1. 测试用户转换为客户
    console.log("1. 测试用户转换为客户...");
    const convertResponse = await api.post(
      "/admin/crm/integration/convert-user-to-customer",
      {
        userId: "test-user-id", // 需要替换为实际的用户ID
        tags: ["用户转换", "测试"],
        notes: "测试用户转换功能",
      }
    );
    // 注意：这个测试可能会失败，因为需要实际的用户ID
    console.log("用户转换测试结果:", convertResponse.data.message);

    // 2. 测试获取用户CRM档案
    console.log("2. 测试获取用户CRM档案...");
    try {
      const profileResponse = await api.get(
        "/admin/crm/integration/user-profile/test-user-id"
      );
      console.log("用户档案测试结果:", profileResponse.data.message);
    } catch (error) {
      console.log(
        "用户档案测试（预期可能失败）:",
        error.response?.data?.message || error.message
      );
    }

    console.log("✅ 系统集成API测试完成");
  } catch (error) {
    console.error(
      "❌ 系统集成API测试失败:",
      error.response?.data || error.message
    );
    // 不抛出错误，因为集成测试可能需要实际数据
  }
}

/**
 * 清理测试数据
 */
async function cleanupTestData() {
  console.log("\n=== 清理测试数据 ===");

  try {
    // 删除跟进记录
    if (testData.followupId) {
      await api.delete(`/admin/crm/followups/${testData.followupId}`);
      console.log("✓ 删除跟进记录");
    }

    // 删除营销活动
    if (testData.campaignId) {
      await api.delete(`/admin/crm/campaigns/${testData.campaignId}`);
      console.log("✓ 删除营销活动");
    }

    // 删除工单
    if (testData.ticketId) {
      await api.delete(`/admin/crm/tickets/${testData.ticketId}`);
      console.log("✓ 删除工单");
    }

    // 删除商机
    if (testData.opportunityId) {
      await api.delete(`/admin/crm/opportunities/${testData.opportunityId}`);
      console.log("✓ 删除商机");
    }

    // 删除线索
    if (testData.leadId) {
      await api.delete(`/admin/crm/leads/${testData.leadId}`);
      console.log("✓ 删除线索");
    }

    // 删除客户
    if (testData.customerId) {
      await api.delete(`/admin/crm/customers/${testData.customerId}`);
      console.log("✓ 删除客户");
    }

    console.log("✅ 测试数据清理完成");
  } catch (error) {
    console.error(
      "❌ 清理测试数据失败:",
      error.response?.data || error.message
    );
  }
}

/**
 * 主测试函数
 */
async function runAllTests() {
  console.log("🚀 开始CRM系统API测试");
  console.log("请确保：");
  console.log("1. 服务器正在运行 (http://localhost:3001)");
  console.log("2. 已设置正确的管理员token");
  console.log("3. 数据库连接正常");

  try {
    await testCustomerAPI();
    await testLeadAPI();
    await testOpportunityAPI();
    await testTicketAPI();
    await testCampaignAPI();
    await testFollowupAPI();
    await testIntegrationAPI();

    console.log("\n🎉 所有CRM API测试通过！");
  } catch (error) {
    console.error("\n💥 测试失败:", error.message);
    process.exit(1);
  } finally {
    // await cleanupTestData();
  }
}

// 运行测试
if (require.main === module) {
  runAllTests();
}

module.exports = {
  runAllTests,
  testCustomerAPI,
  testLeadAPI,
  testOpportunityAPI,
  testTicketAPI,
  testCampaignAPI,
  testFollowupAPI,
  testIntegrationAPI,
};
